package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.Organization;
import com.xmy.cultivate.entity.Quarter;
import com.xmy.cultivate.entity.Staff;
import com.xmy.cultivate.entity.response.YearAndQuarter;
import com.xmy.cultivate.feign.erp_admin.IAdminFeignClient;
import com.xmy.cultivate.respons.ResSchool;
import com.xmy.cultivate.service.IOrganizationService;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.service.IStaffService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 组织机构 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/api/organization")
public class OrganizationController extends BaseController{

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IAdminFeignClient iAdminFeignClient;

    /**
     * @param pageNum
     * @param pageSize
     * @param type
     * @param schoolId
     * @return
     */
    @GetMapping("/findAllSchool")
    public Result findAllSchool(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "1000") Integer pageSize,
                                @RequestParam(value = "type", defaultValue = "") String type,
                                @RequestParam(value = "name", defaultValue = "", required = false) String name,
                                @RequestParam(value = "status", defaultValue = "") String status,
                                @RequestParam(value = "schoolId", defaultValue = "") String schoolId) {
        try {
            return iAdminFeignClient.organizationFindAllSchool(pageNum, pageSize, type, name, status, schoolId);
        } catch (Exception e) {
            return new Result(Code.ERROR, "", "系统更新中，请1分钟后使用");
        }
    }

    /**
     *
     * @param pageNum
     * @param pageSize
     * @param type
     * @param schoolId
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @GetMapping()
    public Result findAll(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize",defaultValue = "1000") Integer pageSize,
                          @RequestParam(value = "type",defaultValue = "") String type,
                          @RequestParam(value = "schoolId",defaultValue = "") String schoolId,
                          @RequestParam(value = "yearPart",defaultValue = "",required = false) String yearPart,
                          @RequestParam(value = "quarterNum",defaultValue = "",required = false) String quarterNum,
                          @RequestParam(value = "isGetAll",defaultValue = "0",required = false) Integer isGetAll) {
        try {
            Quarter quarterNow = iQuarterService.getNowQuarter();

            if (StringUtils.isBlank(yearPart)){
                yearPart = quarterNow.getYearPart().toString();
            }
            if (StringUtils.isBlank(quarterNum)){
                quarterNum = quarterNow.getNum().toString();
            }

            IPage<Organization> iPage = new Page<>(pageNum, pageSize);
            QueryWrapper<Organization> organQueryWrapper = new QueryWrapper<>();
            organQueryWrapper.eq("deleted", 0);
            organQueryWrapper.eq(StringUtils.isNotBlank(type), "type", type);

            if (StringUtils.isNotBlank(schoolId)) {
                organQueryWrapper.eq("id", schoolId);
            } else {
                if (this.isSuper.equals(1)) {
                    if (isGetAll.equals(0)){
                        if (StringUtils.isBlank(yearPart) && StringUtils.isBlank(quarterNum)){
                            yearPart = quarterNow.getYearPart().toString();
                            quarterNum = quarterNow.getNum().toString();
                        }
                        if (StringUtils.isNotBlank(yearPart) && StringUtils.isNotBlank(quarterNum)){
                            //organQueryWrapper.inSql("id","select school_id from order_apply where deleted = 0 and status <>2 and order_type in(1,5) and lesson_type =1 and year_part = "+yearPart+" and quarter_num = "+quarterNum+" group by school_id");
                            organQueryWrapper.inSql("id","select school_id from school_quarter where deleted = 0 and year_part = "+yearPart+" and quarter_num = "+quarterNum+" group by school_id");
                        }
                    }
                } else {
                    organQueryWrapper.in("id", this.baseSchoolIdList);
                }
            }
            iOrganizationService.page(iPage, organQueryWrapper);
            for (Organization organization:iPage.getRecords()){
                Staff staff = iStaffService.getById(organization.getManageId());
                if (staff != null){
                    organization.setManageName(staff.getName());
                }
                if (organization.getType().equals(1)){
                    organization.setTypeName("校区");
                }else {
                    organization.setTypeName("部门");
                }
            }

            return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
        } catch (Exception e) {
            return new Result(Code.ERROR, "", e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") String id){
        try{
            Organization organization = iOrganizationService.getById(id);
            //long ids =  idWorker.nextId();
            //System.out.println(ids);
            return new Result(Code.OK,organization);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }


    @PostMapping()
    public Result save(@RequestBody Organization organization){
        try{
            //dict.setId(idWorker.nextId());
            boolean rs = iOrganizationService.save(organization);
            return new Result(rs?Code.OK:Code.ERROR);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id,@RequestBody Organization organization){
        try{
            boolean rs = iOrganizationService.updateById(organization);
            return new Result(rs?Code.OK:Code.ERROR);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id){
        try{
            boolean rs =  iOrganizationService.removeById(id);
            return new Result(rs?Code.OK:Code.ERROR);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }

    @GetMapping("/getSchoolForYearAndNum")
    public Result getSchoolForYearAndNum(@RequestParam(value = "yearPart",required = false) Integer[] yearPart,
                                         @RequestParam(value = "quarterNum",required = false) Integer[] quarterNum){
        List<YearAndQuarter> yearAndQuarterList = new ArrayList<>();
        for (Integer itemYear:yearPart) {
            for (Integer itemNum:quarterNum){
                YearAndQuarter yearAndQuarter = new YearAndQuarter();
                yearAndQuarter.setYearPart(itemYear);
                yearAndQuarter.setQuarterNum(itemNum);
                yearAndQuarterList.add(yearAndQuarter);
            }
        }

        List<ResSchool> schoolList =  iOrganizationService.getSchoolForYearAndNum(yearAndQuarterList);
        return new Result(Code.OK,schoolList,"");
    }
}
